<template>
  <template v-if="loaded">
    <ProForm
      ref="formRef"
      :model="formState"
      :items="items"
      :disabled="readonly"
      :onValuesChange="onValuesChange"
      :formColLayout="formColLayout()"
      :requiredMark="!readonly"
      class="pro-form-modal"
      v-bind="formProps"
    >
    </ProForm>
    <Row align="middle">
      <Col :span="8">
        <div id="video" v-if="formState.isOpenRtmp == '1'">
          <video
            ref="video"
            controls
            style="width: 95%; object-fit: fill"
          ></video></div
      ></Col>
      <Col :span="16"
        ><KeyBoard v-show="formState.isOpenkeyBoard" :pageData="pageData"
      /></Col>
    </Row>
    <FooterButtons
      :formState="formState"
      :formRef="formRef"
      v-model:readonly="readonly"
      :serviceApi="updatertmpConfig"
      @refresh="refresh"
      :fastConfig="fastConfig"
    />
  </template>
</template>

<script setup lang="tsx">
import {
  computed,
  nextTick,
  onBeforeUnmount,
  ref,
  shallowRef,
  watch,
} from 'vue';
import { useUserStore } from '@/stores/modules';
import { Segmented } from 'ant-design-vue';
import { Col, Row, message } from 'ant-design-vue';
import { ProForm, ProFormProps } from '@/components/ProForm';
import { ItemProps } from '@/components/ProForm/interface';
import {
  addRemoteUser,
  getRemoteUser,
  getrtmpConfig,
  remoteKeyboard,
  updatertmpConfig,
} from '@/api/device';
import FooterButtons from './FooterButtons.vue';
import KeyBoard from './KeyBoard.vue';
import JSWebrtc from './jswebrtc';

defineOptions({
  name: 'Rtmp',
});

interface Props {
  pageData: any;
  fastConfig?: boolean;
}
const props = defineProps<Props>();
const loaded = ref(false);
const readonly = ref(true);
const formRef = shallowRef();
const video = shallowRef();
const formState = ref<Record<string, any>>({});
const column = 3;
const formColLayout = () => {
  const num = 24 / column;
  return { xs: num, sm: num, md: num, lg: num };
};
const formProps = computed<ProFormProps>(() => {
  return {
    labelCol: { span: 5 },
    wrapperCol: { span: 20 },
  };
});
const onValuesChange = (
  values: Record<string, any>,
  state: Record<string, any>,
) => {
  formState.value = {
    ...formState.value,
    ...state,
  };
};
const refresh = () => {
  loaded.value = false;
  nextTick(() => {
    loaded.value = true;
  });
};
const itemObj = (
  label: string,
  type: any,
  field: string,
  required: boolean = false,
  props?: any,
  layout?: any,
  rules: any = [],
): ItemProps => {
  return {
    label,
    type,
    field,
    props: {
      placeholder: `请${type == 'input' ? '输入' : '选择'}${label}`,
      allowClear: false,
      ...props,
    },
    rules: [
      {
        required,
        message: `请${type == 'input' ? '输入' : '选择'}${label}`,
        trigger: 'blur',
      },
      ...rules,
    ],
    ...layout,
  };
};
const itemRender = (title: string): ItemProps => {
  return {
    label: { title },
    type: 'input',
    field: 'h5',
    formItemRender() {
      return <h5 class='h5'>{title}</h5>;
    },
  };
};
const userStore = useUserStore();
let timer = null;
const isDisabled = ref(true);
setTimeout(() => {
  isDisabled.value = false;
}, 5000);
let player: any = null;
const userList = ref('');
watch(
  [() => formState.value.isOpenRtmp, () => formState.value.rtmpUrl],
  ([newIsOpenRtmp, newRtmpUrl]) => {
    player?.destroy();
    if (newIsOpenRtmp == '1') {
      nextTick(() => {
        const url = `webrtc://${newRtmpUrl}/live/${props.pageData.code}`;
        player = new JSWebrtc.Player(url, {
          video: video.value,
          autoplay: true,
        });
      });
    }
  },
);

const items = computed<ProFormProps['items']>(() => [
  itemRender('远程配置'),
  itemObj(
    '开关',
    'switch',
    'isOpenRtmp',
    false,
    {
      unCheckedValue: '0',
      unCheckedChildren: '关闭',
      checkedValue: '1',
      checkedChildren: '开启',
      async onChange(value: any) {
        const isOpenRtmp = value;
        const res = await updatertmpConfig({ ...formState.value, isOpenRtmp });
        message.success(res.msg);
        isDisabled.value = true;
        setTimeout(() => {
          isDisabled.value = false;
        }, 5000);
      },
    },
    { disabled: isDisabled.value },
  ),
  itemObj(
    '键盘',
    'switch',
    'isOpenkeyBoard',
    true,
    {
      unCheckedValue: false,
      unCheckedChildren: '关闭',
      checkedValue: true,
      checkedChildren: '开启',
    },
    { disabled: false },
  ),
  itemObj('设备', 'input', 'rtmpPushType', true, undefined, {
    customRender(state: any) {
      console.log(formState, '5555555555');
      return (
        <Segmented
          v-model:value={formState.value.rtmpPushType}
          disabled={isDisabled.value}
          options={[
            { value: '0', label: '屏幕' },
            { value: '1', label: '摄像头' },
          ]}
          onChange={async (value) => {
            const res = await updatertmpConfig({
              ...formState.value,
            });
            isDisabled.value = true;
            message.success(res.msg);
            setTimeout(() => {
              isDisabled.value = false;
            }, 5000);
          }}
        />
      );
    },
  }),
  itemObj('地址', 'input', 'rtmpUrl', true),
  itemObj('操作用户', 'input', 'userList', false, undefined, {
    customRender(formState: any) {
      return <span>{userList.value}</span>;
    },
  }),
]);

getrtmpConfig(props.pageData.code).then((res: any) => {
  formState.value = res.data;
  formState.value.code = props.pageData.code;
  formState.value.isOpenkeyBoard = false;
  loaded.value = true;
});

timer = setInterval(async () => {
  getrtmpConfig(props.pageData.code).then((res: any) => {
    if (readonly.value) {
      const code = props.pageData.code;
      formRef.value.setFieldsValue({ ...res.data, code });
    } else {
      formRef.value.setFiledValue('isOpenRtmp', res.data.isOpenRtmp);
    }
  });
  const res: any = await getRemoteUser(props.pageData.code);
  userList.value = res.data.join();
  if (formState.value.isOpenRtmp == '1') {
    await addRemoteUser({
      userName: userStore.userName,
      deviceCode: props.pageData.code,
    });
    await remoteKeyboard({
      code: props.pageData.code,
      key: '1000',
    });
  }
}, 5000);

onBeforeUnmount(() => {
  clearInterval(timer);
  player?.destroy();
});
</script>
